package net.qiujuer.library.clink.core;

import net.qiujuer.library.clink.impl.SocketChannelAdapter;

import java.io.Closeable;
import java.io.IOException;
import java.nio.channels.SocketChannel;
import java.util.UUID;

public abstract class Connector implements Closeable, SocketChannelAdapter.OnChannelStatusChangedListener {
    protected UUID key = UUID.randomUUID(); // 唯一的标识一个连接
    private SocketChannel channel;
    private Sender sender;
    private Receiver receiver;

    public void setup(SocketChannel socketChannel) throws IOException {
        this.channel = socketChannel;

        IoContext context = IoContext.get();
        SocketChannelAdapter adapter = new SocketChannelAdapter(channel, context.getIoProvider(), this);
        this.sender = adapter;
        this.receiver = adapter;
        this.readNextMessage();
    }

    private void readNextMessage() {
        if (receiver!=null) {
            try {
                receiver.receiveASync(echoReceiveListener);
            } catch (java.lang.Exception e) {
                System.out.println("开始接受数据异常："+e.getMessage());
            }
        }
    }

    private IoArgs.IoArgsEventListener echoReceiveListener = new IoArgs.IoArgsEventListener(){

        @Override
        public void onStarted(IoArgs args) {

        }

        @Override
        public void onCompleted(IoArgs args) {
            // 打印
            onReceivedNewMessage(args.bufferString());
            // 读取下一条数据
            readNextMessage();
        }

    };

    protected  void onReceivedNewMessage(String str){
        System.out.println(key.toString()+":"+str);
    }

    public void onChannelClosed(SocketChannel channel) {

    }


}
